package com.shenhangye.pushlive.util

import android.os.Environment
import android.util.Log
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

object FileUtils {
    @Throws(IOException::class)
    fun getBytes(path: String?): ByteArray {
        val `is`: InputStream = DataInputStream(FileInputStream(File(path)))
        var len: Int
        val size = 1024
        val bos = ByteArrayOutputStream()
        var buf = ByteArray(size)
        while ((`is`.read(buf, 0, size).also { len = it }) != -1) bos.write(buf, 0, len)
        buf = bos.toByteArray()
        return buf
    }

    fun writeBytes(array: ByteArray?) {
        var writer: FileOutputStream? = null
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            writer = FileOutputStream(
                Environment.getExternalStorageDirectory().toString() + "/codec.h264", true
            )
            writer.write(array)
            writer.write('\n'.code)
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                writer?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
    fun byteArrayToInt(b: ByteArray): Int {
//        if (b[3]<0){
//            return 0;
//        }
        return b[3].toInt() and 0xFF or (
                (b[2].toInt() and 0xFF) shl 8) or (
                (b[1].toInt() and 0xFF) shl 16) or (
                (b[0].toInt() and 0xFF) shl 24)
    }

    private const val TAG = "FileUtils"
    fun writeContent(array: ByteArray): String {
        val HEX_CHAR_TABLE = charArrayOf(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        )
        val sb = StringBuilder()
        for (b in array) {
            sb.append(HEX_CHAR_TABLE[b.toInt() and 0xf0 shr 4])
            sb.append(HEX_CHAR_TABLE[b.toInt() and 0x0f])
        }
        Log.e(TAG, sb.toString())
        //        FileWriter writer = null;
//        try {
//            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
//            writer = new FileWriter(Environment.getExternalStorageDirectory()+"/codec.txt", true);
//            writer.write(sb.toString());
//            writer.write("\n");
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if(writer != null){
//                    writer.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        return sb.toString()
    }
}
